
from PyQt5.Qt import *
import pyqtgraph as pg
import cgitb
from UI.settingdockwidget import Ui_settingDockWidget
from windows.disableeditor import DisableEditor
cgitb.enable(format='text')
pg.setConfigOptions(antialias=True)

class SettingDockWidget(Ui_settingDockWidget, QDockWidget):

    def __init__(self, parent=None):
        super(SettingDockWidget, self).__init__(parent)
        self.setupUi(self)
        self.treeWidgetSetting.setItemDelegateForColumn(0, DisableEditor(self.treeWidgetSetting))

        self.path_setting: QTreeWidgetItem = self.treeWidgetSetting.findItems("路径设置", Qt.MatchExactly)[0]
        self.freq_range_setting: QTreeWidgetItem = self.treeWidgetSetting.findItems("训练频段设定", Qt.MatchExactly)[0]
        self.model_manage: QTreeWidgetItem = self.treeWidgetSetting.findItems("模型管理", Qt.MatchExactly)[0]

        # self.trainModelMethod:QTreeWidgetItem = self.treeWidgetSetting.findItems("模型训练方法", Qt.MatchExactly)[0]

        self.fft_setting:QTreeWidgetItem = self.treeWidgetSetting.findItems("STFT相关设置", Qt.MatchExactly)[0]
        # self.comboBox_method = QComboBox(self)
        # self.comboBox_method.addItems(['单频段单模型', '多频段单模型'])
        # self.treeWidgetSetting.setItemWidget(self.trainModelMethod, 1, self.comboBox_method)

        self.spinbox_nperseg = QSpinBox(self)
        self.spinbox_nperseg.setMinimum(0)
        self.spinbox_nperseg.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(0), 1, self.spinbox_nperseg )


        self.spinbox_noverlap = QSpinBox(self)
        self.spinbox_noverlap.setMinimum(0)
        self.spinbox_noverlap.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(1), 1, self.spinbox_noverlap)

        self.spinbox_nfft = QSpinBox(self)
        self.spinbox_nfft.setMinimum(0)
        self.spinbox_nfft.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(2), 1, self.spinbox_nfft)

        self.spinbox_time_segment = QSpinBox(self)
        self.spinbox_time_segment.setMinimum(0)
        self.spinbox_time_segment.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(3), 1, self.spinbox_time_segment)


        self.double_spinbox_sample_freq = QDoubleSpinBox(self)
        self.double_spinbox_sample_freq.setMinimum(0)
        self.double_spinbox_sample_freq.setMaximum(10000000)

        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(4), 1, self.double_spinbox_sample_freq)

        self.min_freq_double_spin_box = QDoubleSpinBox(self)
        self.min_freq_double_spin_box.setMinimum(0)
        # self.min_freq_double_spin_box.setStyleSheet("border: 0px;")
        self.treeWidgetSetting.setItemWidget(self.freq_range_setting.child(0), 1, self.min_freq_double_spin_box)

        self.max_freq_double_spin_box = QDoubleSpinBox(self)
        self.max_freq_double_spin_box.setMaximum(1000000)
        # self.max_freq_double_spin_box.setStyleSheet("border: 0px;")
        self.treeWidgetSetting.setItemWidget(self.freq_range_setting.child(1), 1, self.max_freq_double_spin_box)

        self.segment_num_spin_box = QSpinBox(self)
        self.segment_num_spin_box.setMaximum(3000)
        # self.segment_num_spin_box.setStyleSheet("border: 0px;")
        self.treeWidgetSetting.setItemWidget(self.freq_range_setting.child(2), 1, self.segment_num_spin_box)

        self.pushButton_confrm_setting.clicked.connect(self.checkGlobalSetting)
        self.added = False
        self.min_freq_double_spin_box.valueChanged.connect(self.ChangeMinFreq)
        self.max_freq_double_spin_box.valueChanged.connect(self.ChangeMaxFreq)
        self.segment_num_spin_box.valueChanged.connect(self.ChangeNumFreq)
        self.comboBox_method.currentTextChanged.connect(self.ChangeNumFreq)
        self.min_val = self.min_freq_double_spin_box.value()
        self.max_val = self.max_freq_double_spin_box.value()
        self.segment = self.segment_num_spin_box.value()

        self.pushButton_recover_default_setting.clicked.connect(self.recoverDefaultSetting)


    def recoverDefaultSetting(self):

        # 路径相关默认设置
        self.path_setting.child(0).setText(1, r"C:\Anomaly Detection")
        self.path_setting.child(1).setText(1, "pictures")
        self.path_setting.child(2).setText(1, "models")

        # 路径相关默认设置
        self.spinbox_nfft.setValue(2048)
        self.spinbox_nperseg.setValue(2048)
        self.spinbox_noverlap.setValue(1024)
        self.spinbox_time_segment.setValue(10)
        self.double_spinbox_sample_freq.setValue(100)
        # 频段设定默认参数
        self.min_freq_double_spin_box.setValue(0)
        self.max_freq_double_spin_box.setValue(0)



    def ChangeMinFreq(self):
        self.added = False

    def ChangeMaxFreq(self):
        self.added = False

    def ChangeNumFreq(self):
        self.added = False

    def checkGlobalSetting(self):
        print("重新分段")
        self.m_name = self.path_setting.child(2).text(1)
        if self.m_name == "":
            self.m_name = "models"
        self.picture_name = self.path_setting.child(1).text(1)
        if self.picture_name == "":
            self.picture_name = "pictures"

        path = self.path_setting.child(0).text(1)
        if path == "":
            path = r"C:\Anomaly Detection"

        self.min_freq = self.min_freq_double_spin_box.value()
        self.min_val = self.min_freq
        self.max_freq = self.max_freq_double_spin_box.value()
        if self.max_freq == self.min_freq:
            QMessageBox(self.parent(), "错误提示", "最小频率和最大频率不能相同!")
            return
        self.max_val = self.max_freq

        if self.segment_num_spin_box.value() > 0:
            self.segment_num = self.segment_num_spin_box.value()
        else:
            self.segment_num = 4

        self.parent().setting_dict["路径设置"] = {}
        if path != "":
            self.parent().setting_dict["路径设置"]["全局保存路径"] = path
            self.parent().setting_dict["路径设置"]["模型文件夹名"] = self.m_name
            self.parent().setting_dict["路径设置"]["图片文件夹名"] = self.picture_name

        self.parent().setting_dict["频率设定"] = {}
        self.parent().setting_dict["频率设定"]["最小频率"] = self.min_freq
        self.parent().setting_dict["频率设定"]["最大频率"] = self.max_freq
        self.segment = self.segment_num
        self.parent().setting_dict["频率设定"]["分段数"] = self.segment_num
        self.span = (self.max_freq - self.min_freq) / self.segment_num
        # 添加阈值条目
        if not self.added:
            cnt = self.model_manage.childCount()
            print(cnt)
            for i in range(cnt):
                self.model_manage.removeChild(self.model_manage.child(cnt - i - 1))

            if self.comboBox_method.currentText() == '单频段单模型':
                print('单频段单模型')
                self.parent().setting_dict["阈值设置"] = {"全部频段": ""}
                a = QTreeWidgetItem(
                    ["全部频段" , ""])
                a.setFlags(Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.model_manage.addChild(a)

            for i in range(self.segment_num):
                a = QTreeWidgetItem(
                    ["%.3f-%.3f" % (i * self.span + self.min_freq, (i + 1) * self.span + self.min_freq), ""])
                a.setFlags(Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.model_manage.addChild(a)
                self.parent().setting_dict["阈值设置"][
                    "%.3f-%.3f" % (i * self.span + self.min_freq, (i + 1) * self.span + self.min_freq)] = None
            self.added = True